package me.pinion.service

import me.pinion.model.Like
import me.pinion.model.ModelType
import me.pinion.model.User
import me.pinion.model.XModel
import me.pinion.model.book.Book
import me.pinion.model.book.Chapter
import me.pinion.model.message.MessageType
import me.pinion.service.Service

/**
 * Created by shao on 14-1-11.
 */
class LikeService extends Service {

    MessageService messageService


    public Like like(XModel<? extends XModel> model, User user) {
        Like like = Like.dao.hasLike(model, user);
        if (like == null) {
            like = new Like();
            like.set("user", user.getId());
            like.set("target_id", model.getId());
            like.set("target_type", ModelType.dao.getByClass(model.getClass()).getId());
            like.save();
            User reciver
            switch (model.class){
                case Book.class:
                    reciver = ((Book)model).author
                    break
                case Chapter.class:
                    reciver = ((Chapter)model).book.author
                    break
                default:
                    reciver = null
            }
            if (reciver){
                messageService.sendMessage(user, reciver, MessageType.LIKE, model)
            }
        }
        return like;
    }
}

